package com.ruoyi.hotel.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import cn.hutool.http.Header;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hotel.domain.HotelInfo;
import com.ruoyi.hotel.domain.HotelRoom;
import com.ruoyi.hotel.mapper.HotelInfoMapper;
import com.ruoyi.hotel.service.IHotelRoomService;
import com.ruoyi.hotel.wx.mp.config.service.WechatTemplateMessageService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import com.ruoyi.hotel.mapper.HotelUserMapper;
import com.ruoyi.hotel.domain.HotelUser;
import com.ruoyi.hotel.service.IHotelUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * 酒店管理Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-12
 */
@Service
public class HotelUserServiceImpl implements IHotelUserService
{

    private static Logger logger = LoggerFactory.getLogger(HotelUserServiceImpl.class);

    @Autowired
    private HotelUserMapper hotelUserMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private HotelInfoMapper hotelInfoMapper;

    @Autowired
    private WechatTemplateMessageService wechatTemplateMessageService;

    @Autowired
    private IHotelRoomService hotelRoomService;


    /**
     * 查询酒店管理
     *
     * @param id 酒店管理主键
     * @return 酒店管理
     */
    @Override
    public HotelUser selectHotelUserById(Long id)
    {
        return hotelUserMapper.selectHotelUserById(id);
    }

    /**
     * 查询酒店管理列表
     *
     * @param hotelUser 酒店管理
     * @return 酒店管理
     */
    @Override
    public List<HotelUser> selectHotelUserList(HotelUser hotelUser)
    {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (StringUtils.isNotNull(loginUser))
        {
            SysUser currentUser = loginUser.getUser();
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
            {
                hotelUser.setUserId(currentUser.getUserId());
            }
        }
        List<HotelUser> hotelUserList = hotelUserMapper.selectHotelUserList(hotelUser);
        //组装房间数据

        for(HotelUser hotel :hotelUserList){
            HotelRoom hotelRoom = new HotelRoom();
            hotelRoom.setHotelId(hotel.getHotelId());
            List<HotelRoom> hotelRoomList = hotelRoomService.selectHotelRoomByHotelId(hotelRoom);
            hotel.setRoomList(hotelRoomList);
        }

        return hotelUserList;
    }

    /**
     * 新增酒店管理
     *
     * @param hotelUser 酒店管理
     * @return 结果
     */
    @Override
    public int insertHotelUser(HotelUser hotelUser)
    {
        hotelUser.setCreateTime(DateUtils.getNowDate());
        return hotelUserMapper.insertHotelUser(hotelUser);
    }

    /**
     * 修改酒店管理
     *
     * @param hotelUser 酒店管理
     * @return 结果
     */
    @Override
    public int updateHotelUser(HotelUser hotelUser)
    {
        HotelUser oldHotelUser = hotelUserMapper.selectHotelUserById(hotelUser.getId());

        if(oldHotelUser == null){
            throw new ServiceException("修改失败!");
        }

        HotelInfo hotelInfo = hotelInfoMapper.selectHotelInfoByHotelId(oldHotelUser.getHotelId());
        if(hotelInfo!=null){
            hotelInfo.setHotelId(hotelUser.getHotelId());
            hotelInfo.setHotelName(hotelUser.getName());
            hotelInfoMapper.updateHotelInfo(hotelInfo);
        }

        hotelUser.setUpdateTime(DateUtils.getNowDate());
        return hotelUserMapper.updateHotelUser(hotelUser);
    }

    /**
     * 批量删除酒店管理
     *
     * @param ids 需要删除的酒店管理主键
     * @return 结果
     */
    @Override
    public int deleteHotelUserByIds(Long[] ids)
    {
        for(Long id : ids){
            HotelUser HotelUser = hotelUserMapper.selectHotelUserById(id);
            HotelInfo hotelInfo = hotelInfoMapper.selectHotelInfoByHotelId(HotelUser.getHotelId());
            if(hotelInfo!=null){
                hotelInfoMapper.deleteHotelInfoById(hotelInfo.getId());
            }
            this.sendHotelMsg(SecurityUtils.getUserId(),HotelUser.getName(),2);
        }
        int result = hotelUserMapper.deleteHotelUserByIds(ids);
        return result;
    }

    /**
     * 删除酒店管理信息
     *
     * @param id 酒店管理主键
     * @return 结果
     */
    @Override
    public int deleteHotelUserById(Long id)
    {
        HotelUser HotelUser = hotelUserMapper.selectHotelUserById(id);
        HotelInfo hotelInfo = hotelInfoMapper.selectHotelInfoByHotelId(HotelUser.getHotelId());
        if(hotelInfo!=null){
            hotelInfoMapper.deleteHotelInfoById(hotelInfo.getId());
        }
        int result = hotelUserMapper.deleteHotelUserById(id);
        return result;
    }


    /**
     * 查询酒店
     *
     * @param hotelUser 酒店信息
     * @return 结果
     */
    @Override
    public List<HotelUser> searchHotel(HotelUser hotelUser)
    {
        List<HotelUser> hotelSearchDomainList= new ArrayList<HotelUser>();
        if(hotelUser.getHotelGroup().equals("jj")){
            hotelSearchDomainList=this.searchJJHotel(hotelUser);
        }

        else if(hotelUser.getHotelGroup().equals("hz")){
            hotelSearchDomainList=this.searchHZHotel(hotelUser);
        }
        else if(hotelUser.getHotelGroup().equals("yd")){
            hotelSearchDomainList=this.searchYDHotel(hotelUser);
        }
        return hotelSearchDomainList;
    }


    public List<HotelUser> searchJJHotel(HotelUser hotelUser){
        List<HotelUser> hotelSearchDomainList= new ArrayList<HotelUser>();
        //请求路径
        String url = "https://wxapp.bestwehotel.com/gw3/app-mini/trip-search-common-foundation/keyword/suggest";
        //使用Restemplate来发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();
        // json对象
        JSONObject jsonObject = new JSONObject();

        // LinkedMultiValueMap 有点像JSON，用于传递post数据，网络上其他教程都使用
        // MultiValueMpat<>来传递post数据
        // 但传递的数据类型有限，不能像这个这么灵活，可以传递多种不同数据类型的参数
        LinkedMultiValueMap body=new LinkedMultiValueMap();
        String param ="{\"languageCode\":0,\"cityCode\":\"AR05223\",\"cityName\":\""+hotelUser.getCityName()+"\",\"keyword\":\""+hotelUser.getKeyword()+"\",\"isDefaultSugMark\":1,\"channelCode\":\"CA00093\"}";
        //设置请求header 为 APPLICATION_FORM_URLENCODED
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("X-WeHotel-Api-Key","815b9911-41e1-4a22-8b23-cb153333a5d1");
        // 请求体，包括请求数据 body 和 请求头 headers
        HttpEntity httpEntity = new HttpEntity(JSONObject.parseObject(param),headers);


        try {
            //使用 exchange 发送请求，以String的类型接收返回的数据
            //ps，我请求的数据，其返回是一个json
            ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.POST,httpEntity,String.class);
            //解析返回的数据
            System.out.println(strbody.getBody());
            JSONObject jsTemp = JSONObject.parseObject(strbody.getBody());

            JSONArray keywordListArr = jsTemp.getJSONArray("data");
            if(keywordListArr!=null && keywordListArr.size()>0){
                for(int i=0;i<keywordListArr.size();i++){
                    JSONObject tempJson = keywordListArr.getJSONObject(i);
                    if(tempJson.getString("zoomType").equals("2")){
                        HotelUser hotelSearchDomain = new HotelUser();
                        hotelSearchDomain.setName(tempJson.getString("zoomName"));
                        hotelSearchDomain.setCityName(tempJson.getString("cityName"));
                        hotelSearchDomain.setHotelId(tempJson.getString("id"));
                        hotelSearchDomain.setHotelGroup("jj");
                        hotelSearchDomainList.add(hotelSearchDomain);
                    }
                }
            }
        }catch (Exception e){
            System.out.println(e);
        }

        return hotelSearchDomainList;
    }



    public List<HotelUser> searchYDHotel(HotelUser hotelUser){
        List<HotelUser> hotelSearchDomainList= new ArrayList<HotelUser>();
        //请求路径
        String url = "https://miniapp.yaduo.com/atourlife/miniapp/placeSearch/search?activeId=0&activityId=0&activitySource=ydxcx&appVer=3.24.3&channelId=60001&deviceId=6533d35a-feb2-49f4-aa04-1fb33da80e7d&token=&inactiveId=&platType=6&blackBox=&version=2.0&currentCityName="+hotelUser.getCityName()+"&keyWord="+ hotelUser.getKeyword() +"&latitude=0&longitude=0";
        //使用Restemplate来发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();

        //设置请求header 为 APPLICATION_FORM_URLENCODED
        HttpHeaders headers = new HttpHeaders();
        //headers.setContentType(MediaType.APPLICATION_JSON);
        // 请求体，包括请求数据 body 和 请求头 headers
        HttpEntity httpEntity = new HttpEntity(headers);

        try {
            //使用 exchange 发送请求，以String的类型接收返回的数据
            //ps，我请求的数据，其返回是一个json
            ResponseEntity<String> strbody = restTemplate.exchange(url, HttpMethod.GET,httpEntity,String.class);
            //解析返回的数据
            System.out.println(strbody.getBody());
            JSONObject jsTemp = JSONObject.parseObject(strbody.getBody());

            if(jsTemp.getInteger("retcode")==0){
                JSONObject result = jsTemp.getJSONObject("result");
                JSONArray keywordListArr = result.getJSONArray("currentCity");
                if(keywordListArr!=null && keywordListArr.size()>0){
                    for(int i=0;i<keywordListArr.size();i++){
                        JSONObject tempJson = keywordListArr.getJSONObject(i);
                        if(tempJson.getString("type").equals("0")){
                            HotelUser hotelSearchDomain = new HotelUser();
                            hotelSearchDomain.setName(tempJson.getString("title"));
                            hotelSearchDomain.setCityName(tempJson.getString("cityName"));
                            hotelSearchDomain.setHotelId(tempJson.getString("chainId"));
                            hotelSearchDomain.setHotelGroup("yd");
                            hotelSearchDomainList.add(hotelSearchDomain);
                        }
                    }
                }

                JSONArray otherListArr = result.getJSONArray("other");
                if(otherListArr!=null && otherListArr.size()>0){
                    for(int i=0;i<otherListArr.size();i++){
                        JSONObject tempJson = otherListArr.getJSONObject(i);
                        if(tempJson.getString("type").equals("0")){
                            HotelUser hotelSearchDomain = new HotelUser();
                            hotelSearchDomain.setName(tempJson.getString("title"));
                            hotelSearchDomain.setCityName(tempJson.getString("cityName"));
                            hotelSearchDomain.setHotelId(tempJson.getString("chainId"));
                            hotelSearchDomain.setHotelGroup("yd");
                            hotelSearchDomainList.add(hotelSearchDomain);
                        }
                    }
                }
            }
        }catch (Exception e){
            System.out.println(e);
        }

        return hotelSearchDomainList;
    }


    public List<HotelUser> searchHZHotel(HotelUser hotelUser){
        List<HotelUser> hotelSearchDomainList= new ArrayList<HotelUser>();
        //请求路径
        String url = "https://hweb-hotel.huazhu.com/hotels/search/search?cityName="+hotelUser.getCityName()+"&keyword="+hotelUser.getKeyword()+"sortChannelType=E";
        try {

            String resultBody = cn.hutool.http.HttpRequest.get(url)
                    .header(Header.USER_AGENT, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090b11) XWEB/9129")//头信息，多个头信息多次调用此方法即可
                    .header(Header.CONTENT_TYPE,"application/json")
                    .timeout(5000)//超时，毫秒
                    .execute().body();

            //解析返回的数据
            System.out.println(resultBody);
            JSONObject jsTemp = JSONObject.parseObject(resultBody);
            if(jsTemp.getInteger("code")==200){
                JSONArray keywordListArr = jsTemp.getJSONArray("content");
                if(keywordListArr!=null && keywordListArr.size()>0){
                    for(int i=0;i<keywordListArr.size();i++){
                        JSONObject tempJson = keywordListArr.getJSONObject(i);
                        if(tempJson.getString("type").equals("Hotel")){
                            HotelUser hotelSearchDomain = new HotelUser();
                            hotelSearchDomain.setName(tempJson.getString("displayName"));
                            hotelSearchDomain.setCityName(tempJson.getString("cityName"));
                            hotelSearchDomain.setHotelId(tempJson.getString("id"));
                            hotelSearchDomain.setHotelGroup("hz");
                            hotelSearchDomainList.add(hotelSearchDomain);
                        }
                    }
                }
            }
        }catch (Exception e){
            System.out.println(e);
        }

        return hotelSearchDomainList;
    }


    /**
     * 保存酒店信息
     *
     * @param hotelUserList 保存酒店信息
     */
    @Override
    @Transactional
    public void addHotel(List<HotelUser> hotelUserList)
    {
        String maxAddCount = configService.selectConfigByKey("sys.hotel.maxAddCount");
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = loginUser.getUser();
        if (StringUtils.isNotNull(loginUser))
        {
            // 如果是超级管理员，则不限制数量
            if (StringUtils.isNotNull(currentUser) && !currentUser.isAdmin())
            {
                List<HotelUser> hotelUserByUserIdList = hotelUserMapper.selectHotelUserByUserId(currentUser.getUserId());
                if((hotelUserByUserIdList.size()+hotelUserList.size())>Long.parseLong(maxAddCount)){
                    throw new ServiceException("添加失败：超过系统限制添加数量!");
                }
            }
        }

        String operName =loginUser.getUsername();
        Long userId = SecurityUtils.getUserId();
        try
        {

            for (HotelUser hotelUser : hotelUserList)
            {
                List<HotelUser> checkHotelUserList = hotelUserMapper.selectHotelUserByHotelId(hotelUser.getHotelId(),userId);
                if(checkHotelUserList.size()>0){
                    throw new ServiceException(hotelUser.getName()+"已存在");
                }
                hotelUser.setCreateBy(operName);
                hotelUser.setCreateTime(new Date());
                hotelUser.setUpdateTime(new Date());
                hotelUser.setUpdateBy(operName);
                hotelUser.setUserId(userId);
                int row = hotelUserMapper.insertHotelUser(hotelUser);
                if(row>0){
                    HotelInfo hotelInfo =  hotelInfoMapper.selectHotelInfoByHotelId(hotelUser.getHotelId());
                    if(hotelInfo == null){
                        hotelInfo = new HotelInfo();
                        hotelInfo.setHotelId(hotelUser.getHotelId());
                        hotelInfo.setHotelName(hotelUser.getName());
                        hotelInfo.setHotelGroup(hotelUser.getHotelGroup());
                        hotelInfo.setCityName(hotelUser.getCityName());
                        hotelInfoMapper.insertHotelInfo(hotelInfo);
                    }
                }

                this.sendHotelMsg(userId,hotelUser.getName(),1);
            }
        }
        catch (Exception e)
        {
            throw new ServiceException("添加失败：" + e.getMessage());
        }
    }


    public void sendHotelMsg(Long userId,String hotelName,int type){
        SysUser sysUser = sysUserService.selectUserById(userId);
        String keyword1 = "";
        String keyword2 = hotelName;
        if(sysUser!= null && !StringUtils.isEmpty(sysUser.getOpenid())){
            //hotelRoomListService.sendHotelTemplateMsg(sysUser.getOpenid(),);
            //String first = "尊敬的[" +sysUser.getPhonenumber()+"]用户";
            if(type == 1){
                keyword1 = "增加酒店提醒";
            }
            else {
                keyword1 = "删除酒店提醒";
            }
            String remark = "您关注的酒店列表已更新，系统每30分钟更新一次状态，请关注微信公众号！";
            wechatTemplateMessageService.sendMsg(sysUser.getOpenid(),"lkrpK2xvMoJ1acFJOBeLUDk3u4E2XIHz9gs1PgGoUb4","",keyword1,keyword2,"",remark,"");
        }
    }
}
